﻿using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace DiskUsage.CoreLib
{
    class SizeStore : ISizeStore
    {
        private Dictionary<string, long> m_size;
        private object m_lock = new object();

        public SizeStore()
        {
            InitializeSizeStore();
            CreateCleaningThread();
        }

        private void CreateCleaningThread()
        {
           new Timer(Compact, null, 0, 120000);
        }

        public long GetSize(string path)
        {
            lock (m_lock)
            {
                if (m_size == null || !m_size.ContainsKey(path))
                    return 0;
                return m_size[path];
            }
        }

        public void SetSize(string path, long size)
        {
            if (m_size == null)
                InitializeSizeStore();
            lock (m_lock)
            {
                m_size[path] = size;
            }
        }

        private void InitializeSizeStore()
        {
            lock (m_lock)
            {
                m_size = new Dictionary<string, long>();
            }
        }

        /// <summary>
        /// Locking is needed because this method will run from
        /// a seperate thread.
        /// </summary>
        private void Compact(object state)
        {
            if (m_size == null) return;
            List<string> badKeys = new List<string>();
            lock (m_lock)
            {
                foreach (var key in m_size.Keys)
                    if (!File.Exists(key))
                        badKeys.Add(key);
                foreach (var badKey in badKeys)
                    m_size.Remove(badKey);
            }
        }
    }
}
